#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <dirent.h>
#include <sys/time.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/socket.h>

#include "data_type.h"
#include "cube.h"
#include "cube_define.h"
#include "cube_record.h"

#include "file_struct.h"
#include "user_define.h"
#include "node_define.h"
#include "data_define.h"

#include "data_auth.h"
extern struct timeval time_val;

char Data_Buf[1024];
int max_data = 250;

RECORD(DATA_DEFINE,ENV_DATA) env_data;

int data_auth_init(void * sub_proc,void * para)
{
	int ret;
    DIR * dir;    
	// add youself's plugin init func here

    dir = opendir("env_data");
    if(dir==NULL)
        system("mkdir env_data");

	return 0;
}

int data_auth_start(void * sub_proc,void * para)
{
	int ret;
	int i;
	void * recv_msg;
	int type;
	int subtype;
	// add yorself's module exec func here

	while(1)
	{
		usleep(time_val.tv_usec);
		ret=ex_module_recvmsg(sub_proc,&recv_msg);
		if(ret<0)
			continue;
		if(recv_msg==NULL)
			continue;
		type=message_get_type(recv_msg);
		subtype=message_get_subtype(recv_msg);
		if(!memdb_find_recordtype(type,subtype))
		{
			printf("message format (%d %d) is not registered!\n",
			message_get_type(recv_msg),message_get_subtype(recv_msg));
			continue;
		}
		if((type==TYPE(DATA_DEFINE))&&(subtype==SUBTYPE(DATA_DEFINE,ENV_DATA)))
		{
			ret=proc_data_auth_collect(sub_proc,recv_msg);
		}
	}
	return 0;
}

int proc_data_auth_collect(void * sub_proc,void * recv_msg)
{
	int ret;
	int i;
    RECORD(DATA_DEFINE,ENV_DATA) * env_data;
    void * type_message;

	ret=message_get_record(recv_msg,&env_data,0);
	if(ret<0)
		return ret;

	DB_RECORD * db_record;
    db_record = memdb_store(env_data,TYPE_PAIR(DATA_DEFINE,ENV_DATA),NULL);
    if(db_record==NULL)
        return -EINVAL;
        type_message=create_type_message(TYPE_PAIR(DATA_DEFINE,ENV_DATA),NULL);
    if(type_message!=NULL)
        ex_module_sendmsg(sub_proc,type_message);

    ret=ex_module_sendmsg(sub_proc,recv_msg);

    return ret;
}
